<template>
    <div class="checkout-bar">
        <div class="select-all">
            <div class="check-circle" @click="toggleSelectAll" :class="{ 'checked': selectAll }">
                <el-icon class="check-icon">
                    <Check />
                </el-icon>
            </div>
            <span class="select-text">全选</span>
        </div>

        <div class="total-wrapper">
            <div class="total-amount">
                <span class="label">合计:</span>
                <span class="price">￥{{ totalPrice.toFixed(2) }}</span>
            </div>
            <button class="checkout-btn" :disabled="count === 0" @click="handleCheckout">
                结算({{ count }})
            </button>
        </div>
    </div>
</template>

<script setup>
import { defineProps, onMounted, ref, watch, defineEmits } from 'vue';
import { Check } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const props = defineProps({
    shopCartData: {
        type: Array,
        default: () => []
    }
});

const emit = defineEmits(['checkout']);
const router = useRouter();

// localShopCartData 不再需要，直接使用 props.shopCartData
const selectAll = ref(false);
const totalPrice = ref(0);
const count = ref(0);

// 核心改进：监听 shopCartData 变化，统一计算总价和数量
watch(() => props.shopCartData, (newCartData) => {
    let sum = 0;
    let cnt = 0;
    let allChecked = true; // 用于判断是否全选

    if (newCartData.length === 0) { // 购物车为空时
        allChecked = false;
    }

    newCartData.forEach(item => {
        if (item.checked) {
            sum += (item.price * item.quantity); // **修正：使用 item.quantity**
            cnt += 1;
        } else {
            allChecked = false; // 只要有一个未选中，就不是全选
        }
    });

    totalPrice.value = Math.max(0, sum);
    count.value = Math.max(0, cnt);
    selectAll.value = allChecked && newCartData.length > 0; // 购物车为空时，全选也应为 false
}, { deep: true, immediate: true }); // 深度监听对象内部变化，并立即执行一次以进行初始计算

const toggleSelectAll = () => {
    const newSelectAllState = !selectAll.value;
    props.shopCartData.forEach(item => {
        item.checked = newSelectAllState; // 直接修改 props.shopCartData 中的 checked 状态，watch 会响应并重新计算
    });
    // totalPrice 和 count 会由上面的 watch 自动更新，这里不需要手动计算
    // selectAll.value 也会由 watch 自动更新，这里也不需要手动设置
};

// 处理结算按钮点击
const handleCheckout = () => {
    // 获取选中的商品
    const selectedItems = props.shopCartData.filter(item => item.checked);

    // 验证是否有选中商品
    if (selectedItems.length === 0) {
        ElMessage.warning('请选择要结算的商品');
        return;
    }

    // 验证商品信息完整性
    const invalidItems = selectedItems.filter(item =>
        !item.productId || !item.price || !item.quantity
    );

    if (invalidItems.length > 0) {
        ElMessage.error('商品信息不完整，请刷新购物车后重试');
        return;
    }

    // 发射事件给父组件，或者直接跳转
    emit('checkout', {
        selectedItems,
        totalPrice: totalPrice.value,
        totalCount: count.value
    });

    // 跳转到结算页面，将选中商品信息通过路由传递
    router.push({
        name: 'checkout',
        query: {
            items: JSON.stringify(selectedItems),
            total: totalPrice.value.toFixed(2)
        }
    });
};

</script>

<style scoped>
/* 你的样式保持不变 */
.checkout-bar {
    position: fixed;
    bottom: 59px;
    left: 0;
    right: 0;
    height: 50px;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 10px;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
    z-index: 100;
}

/* 全选区域 */
.select-all {
    display: flex;
    align-items: center;
    cursor: pointer;
}

.check-circle {
    width: 18px;
    height: 18px;
    border-radius: 50%;
    border: 1px solid #ccc;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 8px;
    /* transition: all 0.2s; */
}

/* 选中状态 - 使用时添加到 check-circle */
.check-circle.checked {
    background: #ff5000;
    border-color: #ff5000;
}

.check-icon {
    width: 12px;
    height: 12px;
    color: white;
}

.select-text {
    font-size: 14px;
    color: #333;
}

/* 总计金额 */
.total-wrapper {
    display: flex;
    align-items: center;
    margin-left: auto;
    /* 关键：将整个区块推到最右侧 */
}

.total-amount {
    display: flex;
    align-items: baseline;
    /* 保持文字基线对齐 */
    margin-right: 15px;
    white-space: nowrap;
    /* 防止换行 */
}

.label {
    font-size: 14px;
    color: #333;
}

.price {
    color: #ff5000;
    font-weight: bold;
    font-size: 16px;
    margin-left: 5px;
}

/* 结算按钮 */
.checkout-btn {
    background: #ff5000;
    color: white;
    border: none;
    height: 40px;
    min-width: 100px;
    padding: 0 20px;
    border-radius: 20px;
    font-size: 15px;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    overflow: hidden;
}

/* 禁用状态 - 使用时添加到 checkout-btn */
.checkout-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
}

/* 两侧半圆效果 */
.checkout-btn::before,
.checkout-btn::after {
    content: '';
    position: absolute;
    width: 20px;
    height: 40px;
    background: #ff5000;
}

.checkout-btn::before {
    left: -10px;
    border-radius: 0 20px 20px 0;
}

.checkout-btn::after {
    right: -10px;
    border-radius: 20px 0 0 20px;
}

/* 禁用状态的半圆 */
.checkout-btn:disabled::before,
.checkout-btn:disabled::after {
    background: #ccc;
}
</style>